<?php
/**
* 后台权限分析
*
* PHP version 5
*
* @package   Ecga
* @author    sunfengming <sunfengming@ec3s.com>
* @copyright 2010 Xingchangxinda Inc.
* @version   SVN: $Id$
*/

namespace Project\Apps\Ecga\Library;

use \XMLReader, \Exception;
use \Project\Apps\Ecga\Application;

/**
* 后台权限分析
*
* PHP version 5
*
* @package   Ecga
* @author    sunfengming <sunfengming@ec3s.com>
* @copyright 2010 Xingchangxinda Inc.
* @version   Release: <0.1>
*/

class AdminAuth
{
	/**
	 * 解析权限配置并返回权限数组
	 * 
	 * @throws Exception
	 * @return array 权限数组
	 * @author sunfengming
	 */
	public static function parseAuthFile()
	{
		$reader = new XMLReader();
		$xmlPath = self::_getAuthFilePath();
		try {
			$reader->xml(file_get_contents($xmlPath));
		} catch (Exception $e) {
			throw new Exception("权限配置文件 $xmlPath 读取错误！");	
		}
		$result = array();
		while ($reader->read()) {
			if (XMLReader::ELEMENT == $reader->nodeType) {
				switch ($reader->name) {
				case 'controller':
					$controller = $reader->getAttribute('name');
					$controllerTitle = $reader->getAttribute('title');
					break;
				case 'group':
					$group = $reader->getAttribute('title');
					break;
				case 'action':
					$action = $reader->readString();
					$result[$controller . '-' . $action] = array($controllerTitle, $group);
					break;
				case 'table':
					$table = $reader->readString();
					$result[$table] = array($controllerTitle, $group);
					break;
				default:
					break;
				}
			}
		}
		$reader->close();
		return $result;
	}
	
	/**
	 * 获取权限配置文件路径
	 * 
	 * @return string|boolean 配置文件路径
	 * @author sunfengming
	 */
	private static function _getAuthFilePath()
	{
		$appPath = Application::getInstance()->getPath();
		$authFilePath = $appPath . DIRECTORY_SEPARATOR . 'config' . 
			DIRECTORY_SEPARATOR . 'adminauth.xml';
		if (is_file($authFilePath)) {
			return $authFilePath;
		} else {
			return false;
		}
	}
}
